package com.fintech.third.service.facerecog;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.fintech.common.enums.RespStatus;
import com.fintech.common.service.BaseServiceImpl;
import com.fintech.common.util.PropertiesUtils;
import com.fintech.common.utils.HttpClientEntityPost;
import com.fintech.third.constant.LocalStatus;
import com.fintech.third.constant.ThirdMethodConstants;
import com.fintech.third.constant.ThirdProductChannelConstant;
import com.fintech.third.model.ThirdProperties;
import com.fintech.third.model.facerecog.BankCardIdentificationResponse;
import com.fintech.third.model.facerecog.BankCardOcrResult;
import com.fintech.third.model.facerecog.FaceCompareResponse;
import com.fintech.third.model.facerecog.IdCardOcrResult;
import com.fintech.third.model.facerecog.StIdCardOcrResult;
import com.fintech.third.utils.Base64Util;
import com.fintech.third.utils.DateUtil;
import com.fintech.third.utils.ThirdPropertiesInitUtil;
import com.fintech.third.utils.ThirdSystemUtil;
import com.marvels.common.utils.MarvelsLogUtil;

import net.sf.json.JSONObject;

@Service("ShangT")
public class ShangTImpl extends BaseServiceImpl implements ShangTService {
	@Override
	public FaceCompareResponse idVerification(Map<String, String> map) {
		FaceCompareResponse faceCompareResponse=new FaceCompareResponse();
		/*
		 * 如果接口停用，直接返回（视具体情况，有的返回停用，有的返回相关值） ADD BY TUXU 2018-05-31
		 */
		if (PropertiesUtils.isTurnOffForSwitch("switch.st0001")) {
			// RespStatus.DISABLE只有接口停用时才使用定义的这个参数，其它情况按原本的来
			faceCompareResponse.setErrorCode(RespStatus.DISABLE.getCode());
			faceCompareResponse.setErrorMsg(RespStatus.DISABLE.getMsg());
			return faceCompareResponse;
		}
		String status = LocalStatus.REQUEST_FAIL.getCode(); // 默认请求失败
		String thirdCode = null;
		Date responseDate = null;
		Date startDate = new Date();
		ThirdProperties thirdProperties=ThirdPropertiesInitUtil.getThirdProperties();
		faceCompareResponse.setChannelCode(ThirdProductChannelConstant.SHANGTANG.getCode());
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("api_id",thirdProperties.getSt_api_id());
		jsonObject.put("api_secret",thirdProperties.getSt_api_secret());
		jsonObject.put("id_number", map.get("id_number"));
		jsonObject.put("user_name", map.get("user_name"));
		String resultStr = "";
		MarvelsLogUtil.getInstance().info("===========>>>商汤身份证验证请求参数:" + jsonObject);
		try {
			resultStr = HttpClientEntityPost.httpClientEntityPost(thirdProperties.getSt_idVerificationUrl(), jsonObject);
			MarvelsLogUtil.getInstance().info("===========>>>商汤身份证验证返回参数:" + resultStr);
			responseDate = new Date();
			JSONObject json=new JSONObject();
			json=JSONObject.fromObject(resultStr);
			if(!"OK".equalsIgnoreCase(json.get("status").toString())){
				faceCompareResponse.setErrorCode(-1);
				faceCompareResponse.setErrorMsg(json.get("reason").toString());
				faceCompareResponse.setChannelCode(ThirdProductChannelConstant.SHANGTANG.getCode());
				
				status = LocalStatus.CALL_SUCCESS.getCode(); // 调用成功但业务数据返回非成功状态
				thirdCode = json.get("status") + "";
			}else{
				
				faceCompareResponse.setErrorCode(0);
				faceCompareResponse.setTrue(Boolean.parseBoolean(json.get("validity").toString()));
				faceCompareResponse.setChannelCode(ThirdProductChannelConstant.SHANGTANG.getCode());
				
				status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
				thirdCode = json.get("status") + "";
			}
		} catch (IOException e) {
			MarvelsLogUtil.getInstance().error("===========>>>商汤身份证验证响应:",e);
			faceCompareResponse.setErrorCode(-1);
			faceCompareResponse.setErrorMsg("商汤身份证验证响应异常");
		}
		// 记入统一日志表
		saveDataQueryLog(null,
				map.get("loanId"), null, null, startDate, responseDate, ThirdMethodConstants.ST0001, thirdCode,
				status, "edc_st_data_query_log", "system");
		return faceCompareResponse;

	}

	@Override
	public FaceCompareResponse faceAlignment(Map<String, String> map) {
		FaceCompareResponse faceCompareResponse=new FaceCompareResponse();
		/*
		 * 如果接口停用，直接返回（视具体情况，有的返回停用，有的返回相关值） ADD BY TUXU 2018-05-31
		 */
		if (PropertiesUtils.isTurnOffForSwitch("switch.st0002")) {
			// RespStatus.DISABLE只有接口停用时才使用定义的这个参数，其它情况按原本的来
			faceCompareResponse.setErrorCode(RespStatus.DISABLE.getCode());
			faceCompareResponse.setErrorMsg(RespStatus.DISABLE.getMsg());
			return faceCompareResponse;
		}
		String status = LocalStatus.REQUEST_FAIL.getCode(); // 默认请求失败
		String thirdCode = null;
		Date startDate = new Date();
		Date responseDate = null;
		String resultStr = "";
		ThirdProperties thirdProperties=ThirdPropertiesInitUtil.getThirdProperties();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("api_id", thirdProperties.getSt_api_id());
		jsonObject.put("api_secret", thirdProperties.getSt_api_secret());
		jsonObject.put("id_number", map.get("id_number"));
		jsonObject.put("user_name", map.get("user_name"));
		jsonObject.put("selfie_auto_rotate", true);
		faceCompareResponse.setChannelCode(ThirdProductChannelConstant.SHANGTANG.getCode());
		MarvelsLogUtil.getInstance().info("===========>>>人脸比对请求,loanId"+map.get("loanId")+",参数:" + jsonObject.toString());
		try {
			jsonObject.put("image_base64", map.get("image_base64"));
			resultStr = HttpClientEntityPost.httpClientPost(thirdProperties.getSt_faceAligmentUrl(), jsonObject);
			responseDate = new Date();
			MarvelsLogUtil.getInstance().info("===========>>>人脸比对返回,loanId"+map.get("loanId")+",参数:" + resultStr);
			JSONObject json=new JSONObject();
			json=JSONObject.fromObject(resultStr);
			if("OK".equalsIgnoreCase(json.get("status").toString()) && (boolean)json.getJSONObject("identity").get("validity")){
				faceCompareResponse.setScore(json.get("confidence")==null?"0.1":json.get("confidence").toString());
				faceCompareResponse.setTrue((boolean)json.getJSONObject("identity").get("validity"));
				faceCompareResponse.setErrorCode(0);
			}else{
				faceCompareResponse.setErrorMsg(json.getJSONObject("identity").get("reason").toString());
				faceCompareResponse.setErrorCode(-1);
			}
			if ("OK".equalsIgnoreCase(json.get("status") + "")) {
				status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
			} else {
				status = LocalStatus.CALL_SUCCESS.getCode(); // 调用成功但业务数据返回非成功状态
			}
			thirdCode = json.get("status") + "";
		} catch (IOException e) {
			MarvelsLogUtil.getInstance().error("===========>>>人脸对比,loanId"+map.get("loanId")+",商汤人脸对比响应异常:",e);
			faceCompareResponse.setErrorCode(-1);
			faceCompareResponse.setErrorMsg("商汤人脸对比响应异常");
		}
		// 记入统一日志表
		saveDataQueryLog(null, map.get("loanId"),
				null, null, startDate, responseDate, ThirdMethodConstants.ST0002, thirdCode, status,
				"edc_st_data_query_log", "system");
		
		return faceCompareResponse;

	}

	@Override
	public FaceCompareResponse bankCardIdentification(Map<String, String> map) {
		FaceCompareResponse faceCompareResponse=new FaceCompareResponse();
		/*
		 * 如果接口停用，直接返回（视具体情况，有的返回停用，有的返回相关值） ADD BY TUXU 2018-05-31
		 */
		if (PropertiesUtils.isTurnOffForSwitch("switch.st0003")) {
			// RespStatus.DISABLE只有接口停用时才使用定义的这个参数，其它情况按原本的来
			faceCompareResponse.setErrorCode(RespStatus.DISABLE.getCode());
			faceCompareResponse.setErrorMsg(RespStatus.DISABLE.getMsg());
			return faceCompareResponse;
		}
		String status = LocalStatus.REQUEST_FAIL.getCode(); // 默认请求失败
		String thirdCode = null;
		Date startDate = new Date();
		Date responseDate = null;
		Map<String, String> dataMap=new HashMap<String,String>();
		ThirdProperties thirdProperties=ThirdPropertiesInitUtil.getThirdProperties();
		String base64File=map.get("base64File");
		String fileName=DateUtil.dateFormat2();
		dataMap.put("api_id",thirdProperties.getSt_api_id());
		dataMap.put("api_secret",thirdProperties.getSt_api_secret());
		dataMap.put("url",thirdProperties.getSt_bankCard_distinguishUrl());
		String filePath=Base64Util.generateImage(base64File, fileName, ThirdSystemUtil.class.getResource(thirdProperties.getImage_path()).getPath());
		dataMap.put("file",filePath);
		String resultStr = "";
		MarvelsLogUtil.getInstance().info("===========>>>商汤银行卡识别请求参数:" + JSONObject.fromObject(dataMap));
		try {
			resultStr = HttpClientEntityPost.postStFile(dataMap);
			responseDate = new Date();
			MarvelsLogUtil.getInstance().info("===========>>>商汤银行卡识别返回参数:" + resultStr);
//			status = LocalStatus.IN_DATABASE_FAIL.getCode();
			BankCardIdentificationResponse bankCardIdentificationResponse=new BankCardIdentificationResponse();
			bankCardIdentificationResponse=JSON.parseObject(resultStr, BankCardIdentificationResponse.class);
			if(!"OK".equalsIgnoreCase(bankCardIdentificationResponse.getStatus()) || bankCardIdentificationResponse.getResult()==null){
				faceCompareResponse.setErrorCode(-1);
				faceCompareResponse.setErrorMsg("银行卡识别失败");
				faceCompareResponse.setChannelCode(ThirdProductChannelConstant.SHANGTANG.getCode());
				
				status = LocalStatus.CALL_SUCCESS.getCode(); // 调用成功但业务数据返回非成功状态
			}else{
				faceCompareResponse.setErrorCode(0);
				faceCompareResponse.setErrorMsg("银行卡识别成功");
				BankCardOcrResult bankCardOcrResult =new BankCardOcrResult();
				bankCardOcrResult.setBankIdentificationNumber(bankCardIdentificationResponse.getResult().getBankIdentificationNumber());
				bankCardOcrResult.setBankName(bankCardIdentificationResponse.getResult().getBankName());
				bankCardOcrResult.setCardName(bankCardIdentificationResponse.getResult().getCardName());
				bankCardOcrResult.setCardNumber(bankCardIdentificationResponse.getResult().getCardNumber());
				bankCardOcrResult.setCardType(bankCardIdentificationResponse.getResult().getCardType());
				
				if(StringUtils.isBlank(map.get("freshVersion")) || map.get("freshVersion").equals("0")){//老版本
					faceCompareResponse.setOcrResult(bankCardIdentificationResponse);
				}else{
					faceCompareResponse.setOcrResult(bankCardOcrResult);
				}
				faceCompareResponse.setChannelCode(ThirdProductChannelConstant.SHANGTANG.getCode());
				
				status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
			}
			
			thirdCode = bankCardIdentificationResponse.getStatus();
		} catch (IOException e) {
			MarvelsLogUtil.getInstance().error("===========>>>商汤银行卡识别响应:",e);
			faceCompareResponse.setErrorCode(-1);
			faceCompareResponse.setErrorMsg("银行卡识别响应异常");
			faceCompareResponse.setChannelCode(ThirdProductChannelConstant.SHANGTANG.getCode());
		}
		// 记入统一日志表
		saveDataQueryLog(null, map.get("loanId"),
				null, null, startDate, responseDate, ThirdMethodConstants.ST0003, thirdCode, status,
				"edc_st_data_query_log", "system");
		
		return faceCompareResponse;
	}

	@Override
	public FaceCompareResponse stIdCardIdentification(Map<String, String> map) {
		FaceCompareResponse faceCompareResponse=new FaceCompareResponse();
		/*
		 * 如果接口停用，直接返回（视具体情况，有的返回停用，有的返回相关值） ADD BY TUXU 2018-05-31
		 */
		if (PropertiesUtils.isTurnOffForSwitch("switch.st0004")) {
			// RespStatus.DISABLE只有接口停用时才使用定义的这个参数，其它情况按原本的来
			faceCompareResponse.setErrorCode(RespStatus.DISABLE.getCode());
			faceCompareResponse.setErrorMsg(RespStatus.DISABLE.getMsg());
			return faceCompareResponse;
		}
		String status = LocalStatus.REQUEST_FAIL.getCode(); // 默认请求失败
		String thirdCode = null;
		Date startDate = new Date();
		Date responseDate = null;
		Map<String,String> dataMap=new HashMap<String,String>();
		ThirdProperties thirdProperties=ThirdPropertiesInitUtil.getThirdProperties();
		String base64File=map.get("base64File");
		String fileName=DateUtil.dateFormat2();
		dataMap.put("api_id",thirdProperties.getSt_api_id());
		dataMap.put("api_secret",thirdProperties.getSt_api_secret());
		dataMap.put("url",thirdProperties.getSt_idCard_distinguishUrl());
		dataMap.put("classify","true");
		dataMap.put("auto_rotate", "true");
		String filePath=Base64Util.generateImage(base64File, fileName, ThirdSystemUtil.class.getResource(thirdProperties.getImage_path()).getPath());
		dataMap.put("image_file",filePath);
		String resultStr = "";
		MarvelsLogUtil.getInstance().info("===========>>>商汤身份证识别请求参数:" + JSONObject.fromObject(dataMap));
		try {
			resultStr = HttpClientEntityPost.postStFile2(dataMap);
			responseDate = new Date();
			MarvelsLogUtil.getInstance().info("===========>>>商汤身份证识别返回参数:" + resultStr);
			if(StringUtils.isNotBlank(resultStr)){
				status = LocalStatus.IN_DATABASE_FAIL.getCode();
				StIdCardOcrResult stIdCardOcrResult=new StIdCardOcrResult();
				stIdCardOcrResult=JSON.parseObject(resultStr, StIdCardOcrResult.class);
				if(1000==stIdCardOcrResult.getCode()){
					IdCardOcrResult idCardOcrResult=new IdCardOcrResult();
					idCardOcrResult.setAddress(stIdCardOcrResult.getInfo().getAddress());
					idCardOcrResult.setAuthority(stIdCardOcrResult.getInfo().getAuthority());
					idCardOcrResult.setDay(stIdCardOcrResult.getInfo().getDay());
					idCardOcrResult.setGender(stIdCardOcrResult.getInfo().getGender());
					idCardOcrResult.setMonth(stIdCardOcrResult.getInfo().getMonth());
					idCardOcrResult.setName(stIdCardOcrResult.getInfo().getName());
					idCardOcrResult.setNation(stIdCardOcrResult.getInfo().getNation());
					idCardOcrResult.setNumber(stIdCardOcrResult.getInfo().getNumber());
					idCardOcrResult.setSide(stIdCardOcrResult.getSide());
					idCardOcrResult.setTimelimit(stIdCardOcrResult.getInfo().getTimelimit());
					idCardOcrResult.setYear(stIdCardOcrResult.getInfo().getYear());
					if (!PropertiesUtils.isTurnOffForSwitch("switch.idnumber.ocr.type")) {
						if (StringUtils.isNotEmpty(stIdCardOcrResult.getType())) {
							String type = stIdCardOcrResult.getType();
							if ("normal".equalsIgnoreCase(type)) {
								idCardOcrResult.setType("1");
								faceCompareResponse.setErrorCode(0);
								faceCompareResponse.setErrorMsg("旷视身份证识别成功");
							}else if ("photocopy".equalsIgnoreCase(type)) {
								idCardOcrResult.setType("2");
								faceCompareResponse.setErrorCode(-1);
								faceCompareResponse.setErrorMsg("请使用正常拍摄身份证件");
							}else if ("ps".equalsIgnoreCase(type)) {
								idCardOcrResult.setType("3");
								faceCompareResponse.setErrorCode(-1);
								faceCompareResponse.setErrorMsg("请使用正常拍摄身份证件");
							}else if ("reversion".equalsIgnoreCase(type)) {
								idCardOcrResult.setType("4");
								faceCompareResponse.setErrorCode(-1);
								faceCompareResponse.setErrorMsg("请使用正常拍摄身份证件");
							}else if ("other".equalsIgnoreCase(type)) {
								idCardOcrResult.setType("5");
								faceCompareResponse.setErrorCode(-1);
								faceCompareResponse.setErrorMsg("请使用正常拍摄身份证件");
							}else if ("unknown".equalsIgnoreCase(type)) {
								idCardOcrResult.setType("6");
								faceCompareResponse.setErrorCode(-1);
								faceCompareResponse.setErrorMsg("请使用正常拍摄身份证件");
							}
						}else{
							faceCompareResponse.setErrorCode(0);
							faceCompareResponse.setErrorMsg("识别成功");
						}
					}else{
						faceCompareResponse.setErrorCode(0);
						faceCompareResponse.setErrorMsg("识别成功");
					}
					if(StringUtils.isBlank(map.get("freshVersion")) || map.get("freshVersion").equals("0")){//老版本
						faceCompareResponse.setOcrResult(stIdCardOcrResult);
					}else{
						faceCompareResponse.setOcrResult(idCardOcrResult);
					}
					faceCompareResponse.setChannelCode(ThirdProductChannelConstant.SHANGTANG.getCode());
					status = LocalStatus.SUCCESS_WITH_DATA.getCode(); // 查询成功且有数据
					thirdCode = stIdCardOcrResult.getCode() + "";
				}else{
					faceCompareResponse.setErrorCode(-1);
					faceCompareResponse.setErrorMsg("商汤身份证识别失败");
					faceCompareResponse.setChannelCode(ThirdProductChannelConstant.SHANGTANG.getCode());
					
					status = LocalStatus.CALL_SUCCESS.getCode(); // 调用成功但业务数据返回非成功状态
					thirdCode = stIdCardOcrResult.getCode() + "";
				}
				
			} else {
				status = LocalStatus.CALL_SUCCESS.getCode(); // 调用成功但业务数据返回非成功状态
			}
		} catch (IOException e) {
			MarvelsLogUtil.getInstance().error("===========>>>商汤身份证识别响应:",e);
			faceCompareResponse.setErrorCode(-1);
			faceCompareResponse.setErrorMsg("商汤身份证识别响应异常");
			faceCompareResponse.setChannelCode(ThirdProductChannelConstant.SHANGTANG.getCode());
		}

		// 记入统一日志表
		saveDataQueryLog(null, map.get("loanId"),
				null, null, startDate, responseDate, ThirdMethodConstants.ST0004, thirdCode, status,
				"edc_st_data_query_log", "system");
		return faceCompareResponse;
	}
	
}
